﻿using System;
using System.Collections.Generic;
using System.Linq;
using PaceR.Core.EntityStorage;
using PaceR.Data.Transactions;

namespace PaceR.Data.Context
{
    public class EntityStoreContext : BaseContext
    {
        protected readonly EntityStore _store;
        protected SimpleTransactionManager CurrentTransaction { get { return base._transactionManager as SimpleTransactionManager; } }
        
        public EntityStoreContext(EntityStore store)
            : base(new SimpleTransactionManager())
        {
            if (store == null) throw new ArgumentNullException("store");
            _store = store;
        }

        public override IQueryable<T> Find<T>()
        {
            var collection = _store.GetEntity<IEnumerable<T>>();
            return (collection ?? new List<T>()).AsQueryable();
        }


        public override IQueryable<T> Find<T>(Func<T, bool> where)
        {
            return Find<T>().Where(t => where(t));
        }

        public override T First<T>(Func<T, bool> where)
        {
            return Find<T>().First(t => where(t));
        }

        public override T FirstOrDefault<T>(Func<T, bool> where)
        {
            return Find<T>().FirstOrDefault(t => where(t));
        }

        public override void Save<T>(T record)
        {
            CurrentTransaction.Changes.Add(new SimpleTransactionItem<T>(record, r =>
            {
                var collection = new List<T>(_store.GetEntity<IEnumerable<T>>() ?? new T[0]);
                collection.Add(r);
                _store.SaveEntity<IEnumerable<T>>(collection);
            }));

        }

        public override void Remove<T>(T record)
        {
            CurrentTransaction.Changes.Add(new SimpleTransactionItem<T>(record, r =>
            {
                var collection = new List<T>(_store.GetEntity<IEnumerable<T>>() ?? new T[0]);
                collection.Remove(r);
                _store.SaveEntity<IEnumerable<T>>(collection);
            }));
        }
    }
}
